package dbopr

import (
	"fmt"
	"myCloud/config"
	"myCloud/dbmodel"
	"myCloud/logsvr"
	"time"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

var logger = logsvr.GetLogger("db")
var dbSession *gorm.DB

func DatabaseInit(cfg *config.DatabaseConfig) (err error) {
	return databaseInit(cfg.Provider, cfg.GetUrl(), cfg.Debug)
}

func DatabaseInit2(provider, dbUrl string, debug bool) (err error) {
	return databaseInit(provider, dbUrl, debug)
}

func databaseInit(provider, dbUrl string, debug bool) (err error) {
	if dbSession != nil {
		err = fmt.Errorf("数据库链接被重复初始化。")
		return
	}
	dbSession, err = gorm.Open(provider, dbUrl)
	if err != nil {
		logger.Errorf("gorm.Open %s => [%s] err %s", provider, dbUrl, err)
		return
	}
	dbSession.DB().SetConnMaxLifetime(1 * time.Hour)
	dbSession.DB().SetMaxIdleConns(100)
	dbSession.DB().SetMaxOpenConns(200)
	//设置表名非负数形式
	dbSession.SingularTable(true)

	dbSession.AutoMigrate(
		dbmodel.User{},
		dbmodel.UserToken{},
		dbmodel.ServerInfo{},
		dbmodel.Album{},
		dbmodel.UserDevice{},
		dbmodel.File{},
	)

	dbSession.SetLogger(zapLogger)
	if debug {
		logger.Info("database sql logger enabled.")
		dbSession.LogMode(true)
	} else {
		dbSession.LogMode(false)
	}
	return
}

func GetSession() *gorm.DB {
	return dbSession
}
